package nit.wave.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public final class JdbcUtils {
	static DataSource myDataSource = null;

	private JdbcUtils() {
	}

	static {
		try {
			// Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
			Properties properties = new Properties();
			InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
			properties.load(is);
			myDataSource = BasicDataSourceFactory.createDataSource(properties);
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 链接 @
	 * 
	 * @author shanchang
	 * @return Connection
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		// return DriverManager.getConnection(url, username, password);
		return myDataSource.getConnection();
	}

	/**
	 * 释放内存
	 * 
	 * @param rs
	 *            返回的结果集
	 * @param st
	 *            会话
	 * @param conn
	 *            链接
	 */
	public static void free(ResultSet rs, Statement st, Connection conn) {
		// 层层释放，先从结果集，到Statement对象，最后连接
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}

	}
}
